package chapter07

object Demo14_HighLevelFunction_Map {
  def main(args: Array[String]): Unit = {
    val list = List(1, 2, 3, 4, 5, 6, 7, 8, 9)
    //    (1）过滤
    //    遍历—个集合并从中获取满足指定条件的元素组成—个新的集合
    //选取偶数
    val evenlist = list.filter((elem: Int) => {
      elem % 2 == 0
    })
    println(evenlist)

    println(list.filter(_ % 2 == 0))

    println("=======================")
    //    (2）转化/映射(map)
    //    将集合中的每一个元素映射到某一个函数
    println(list.map(_ * 2))
    println(list.map(x => x * x))
    println("=======================")
    //    (3）扁平化
    //    (4）扁平化+映射注: flatMap相当于先进行map操作，在进行flatten操作
    //    集合中的每个元素的子元素映射到某个函数并返回新集合
    val nestedList: List[List[Int]] = List(List(1, 2, 3), List(4, 5), List(6, 7, 8, 9))
    val flatList = nestedList(0) ::: nestedList(1) ::: nestedList(2)
    println(flatList)

    val nestedList2 = nestedList.flatten
    println(nestedList2)

    //扁平映射
    //将一组字符串分别进行分词并保存成单词
    val strings: List[String] = List("hello word", "hello scala", "hello java")
    //val splitList: List[Array[String]] = strings.map(string => string.split(" "))
    //简化
    val splitList: List[Array[String]] = strings.map(_.split(" ")) //分词
    val flattenList = splitList.flatten
    println(flattenList)

    //扁平加强化
    val flatmapList = strings.flatMap(_.split(" "))
    println(flatmapList)

    println("=======================")

    //    (5）分组(group)
    //    按照指定的规则对集合的元素进行分组

    val groupMap = list.groupBy(_ % 2)
    val groupMap2 = list.groupBy(data => if (data % 2 == 0) "偶数" else "奇数")
    println(groupMap)
    println(groupMap2)
    println("============================")
    //给定一组词汇，按照单词首字母进行分类
    val wordList = List("china", "canada", "america", "bob", "japan", "cary", "alice")
    println(wordList.groupBy(_.charAt(0)))
  }
}
